package com.unbiz.common;
/**
 * java.util.function.* 和org.apache.commons.collections4.* 之间互相转换
 */
import java.util.function.BiConsumer;
import java.util.function.BiFunction;
import java.util.function.BiPredicate;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.function.Predicate;

import org.apache.commons.collections4.Closure;
import org.apache.commons.collections4.Transformer;

import com.unbiz.tuple.Tuple;
import com.unbiz.tuple.Tuple2;
//import org.apache.commons.collections4.Predicate;

public class FunctorUtil {
	
	/**
     * 转换为java.util.function.Predicate
     * @param p
     * @return
     */
    public static <T> Predicate<T> asPredicate(org.apache.commons.collections4.Predicate<T> p) {
        return s -> p.evaluate(s);
    }
    
    /**
     * 转换为commons.collections4.Predicate
     * @param p
     * @return
     */
    public static <T> org.apache.commons.collections4.Predicate<T> asPredicate(Predicate<T> p) {
        return s -> p.test(s);
    }
    
    public static <T,U> org.apache.commons.collections4.Predicate<Tuple2<T,U>> asPredicate(BiPredicate<T,U> p) {
    	return (Tuple2<T,U> s) -> p.test(s._0,s._1);
    }
    
    public static <T,R> Function<T,R> asFunction(Transformer<T,R> t) {
        return s -> t.transform(s);
    }
    
    public static <T,R> Transformer<T,R> asTransformer(Function<T,R> f) {
        return s -> f.apply(s);
    }
    
    public static <T,U,R> Transformer<Tuple2<T,U>,R> asTransformer(BiFunction<T,U,R> f) {
        return (Tuple2<T,U> s) -> f.apply(s._0,s._1);
    }
    
    public static <T> Consumer<T> asConsumer(Closure<T> p) {
        return s -> p.execute(s);
    }
    
    public static <T> Closure<T> asClosure(Consumer<T> p) {
        return s -> p.accept(s);
    }
    
    public static <T,U> Closure<Tuple2<T,U>> asClosure(BiConsumer<T,U> p) {
    	return (Tuple2<T,U> s) -> p.accept(s._0,s._1);
    }
    
}
